document.addEventListener('DOMContentLoaded', function() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    if (!currentUser) {
        alert('请先登录');
        window.location.href = '../login.html';
        return;
    }
    
    // 加载地址列表
    loadAddresses();
    
    // 添加地址按钮点击事件
    document.getElementById('addAddressBtn').addEventListener('click', function() {
        openAddressModal();
    });
    
    // 关闭模态框
    document.querySelector('.close-btn').addEventListener('click', closeAddressModal);
    
    // 地址表单提交
    document.getElementById('addressForm').addEventListener('submit', saveAddress);
    
    // 省份选择变化时加载城市
    document.getElementById('province').addEventListener('change', function() {
        loadCities(this.value);
    });
    
    // 城市选择变化时加载区县
    document.getElementById('city').addEventListener('change', function() {
        loadDistricts(document.getElementById('province').value, this.value);
    });
    
    // 初始化省份数据
    loadProvinces();
});

// 加载地址列表
function loadAddresses() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const addresses = JSON.parse(localStorage.getItem('addresses')) || [];
    const userAddresses = addresses.filter(addr => addr.userId === currentUser.id);
    
    const addressesList = document.getElementById('addressesList');
    addressesList.innerHTML = '';
    
    if (userAddresses.length === 0) {
        addressesList.innerHTML = '<p class="empty-addresses">暂无收货地址</p>';
        return;
    }
    
    userAddresses.forEach(address => {
        const addressCard = document.createElement('div');
        addressCard.className = `address-card ${address.isDefault ? 'default' : ''}`;
        addressCard.innerHTML = `
            <div class="address-header">
                <div>
                    <span class="address-name">${address.name}</span>
                    <span class="address-phone">${address.phone}</span>
                    ${address.isDefault ? '<span class="default-tag">默认</span>' : ''}
                </div>
            </div>
            <div class="address-detail">
                ${address.province} ${address.city} ${address.district} ${address.detail}
            </div>
            <div class="address-actions">
                ${!address.isDefault ? '<button class="set-default-btn" onclick="setDefaultAddress(\'${address.id}\')">设为默认</button>' : ''}
                <button class="edit-btn" onclick="editAddress(\'${address.id}\')">编辑</button>
                <button class="delete-btn" onclick="deleteAddress(\'${address.id}\')">删除</button>
            </div>
        `;
        addressesList.appendChild(addressCard);
    });
}

// 打开地址模态框
function openAddressModal(addressId = null) {
    const modal = document.getElementById('addressModal');
    const modalTitle = document.getElementById('modalTitle');
    const form = document.getElementById('addressForm');
    
    if (addressId) {
        // 编辑模式
        modalTitle.textContent = '编辑收货地址';
        const addresses = JSON.parse(localStorage.getItem('addresses')) || [];
        const address = addresses.find(addr => addr.id === addressId);
        
        if (address) {
            document.getElementById('addressId').value = address.id;
            document.getElementById('name').value = address.name;
            document.getElementById('phone').value = address.phone;
            document.getElementById('detail').value = address.detail;
            document.getElementById('isDefault').checked = address.isDefault;
            
            // 设置地区选择
            loadProvinces(address.province);
            setTimeout(() => {
                document.getElementById('province').value = address.province;
                loadCities(address.province, address.city);
                setTimeout(() => {
                    document.getElementById('city').value = address.city;
                    loadDistricts(address.province, address.city, address.district);
                    setTimeout(() => {
                        document.getElementById('district').value = address.district;
                    }, 100);
                }, 100);
            }, 100);
        }
    } else {
        // 添加模式
        modalTitle.textContent = '添加收货地址';
        form.reset();
        document.getElementById('addressId').value = '';
    }
    
    modal.style.display = 'block';
}

// 关闭地址模态框
function closeAddressModal() {
    document.getElementById('addressModal').style.display = 'none';
}

// 保存地址
function saveAddress(e) {
    e.preventDefault();
    
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const addressId = document.getElementById('addressId').value;
    const name = document.getElementById('name').value.trim();
    const phone = document.getElementById('phone').value.trim();
    const province = document.getElementById('province').value;
    const city = document.getElementById('city').value;
    const district = document.getElementById('district').value;
    const detail = document.getElementById('detail').value.trim();
    const isDefault = document.getElementById('isDefault').checked;
    
    // 验证手机号
    if (!validatePhone(phone)) {
        alert('请输入有效的手机号码');
        return;
    }
    
    // 验证地区选择
    if (!province || !city || !district) {
        alert('请选择完整的地区信息');
        return;
    }
    
    let addresses = JSON.parse(localStorage.getItem('addresses')) || [];
    
    if (addressId) {
        // 更新现有地址
        const index = addresses.findIndex(addr => addr.id === addressId);
        if (index !== -1) {
            addresses[index] = {
                ...addresses[index],
                name,
                phone,
                province,
                city,
                district,
                detail,
                isDefault
            };
        }
    } else {
        // 添加新地址
        const newAddress = {
            id: Date.now().toString(),
            userId: currentUser.id,
            name,
            phone,
            province,
            city,
            district,
            detail,
            isDefault,
            createdAt: new Date().toLocaleString()
        };
        addresses.push(newAddress);
    }
    
    // 如果设置为默认地址，取消其他默认地址
    if (isDefault) {
        addresses = addresses.map(addr => {
            if (addr.userId === currentUser.id && addr.id !== addressId) {
                return { ...addr, isDefault: false };
            }
            return addr;
        });
    }
    
    localStorage.setItem('addresses', JSON.stringify(addresses));
    closeAddressModal();
    loadAddresses();
    alert('地址保存成功');
}

// 加载省份数据
function loadProvinces(selectedProvince = null) {
    // 这里应该是从服务器获取省份数据，这里使用模拟数据
    const provinces = [
        { code: '11', name: '北京市' },
        { code: '31', name: '上海市' },
        { code: '44', name: '广东省' },
        { code: '33', name: '浙江省' },
        { code: '32', name: '江苏省' }
    ];
    
    const provinceSelect = document.getElementById('province');
    provinceSelect.innerHTML = '<option value="">请选择省份</option>';
    
    provinces.forEach(province => {
        const option = document.createElement('option');
        option.value = province.name;
        option.textContent = province.name;
        if (selectedProvince === province.name) {
            option.selected = true;
        }
        provinceSelect.appendChild(option);
    });
    
    // 重置城市和区县选择
    document.getElementById('city').innerHTML = '<option value="">请选择城市</option>';
    document.getElementById('city').disabled = true;
    document.getElementById('district').innerHTML = '<option value="">请选择区县</option>';
    document.getElementById('district').disabled = true;
}

// 加载城市数据
function loadCities(provinceName, selectedCity = null) {
    if (!provinceName) return;
    
    // 模拟城市数据
    const cityData = {
        '北京市': ['北京市'],
        '上海市': ['上海市'],
        '广东省': ['广州市', '深圳市', '珠海市', '佛山市', '东莞市'],
        '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '绍兴市'],
        '江苏省': ['南京市', '苏州市', '无锡市', '常州市', '徐州市']
    };
    
    const cities = cityData[provinceName] || [];
    const citySelect = document.getElementById('city');
    citySelect.innerHTML = '<option value="">请选择城市</option>';
    
    cities.forEach(city => {
        const option = document.createElement('option');
        option.value = city;
        option.textContent = city;
        if (selectedCity === city) {
            option.selected = true;
        }
        citySelect.appendChild(option);
    });
    
    citySelect.disabled = false;
    
    // 重置区县选择
    document.getElementById('district').innerHTML = '<option value="">请选择区县</option>';
    document.getElementById('district').disabled = true;
}

// 加载区县数据
function loadDistricts(provinceName, cityName, selectedDistrict = null) {
    if (!provinceName || !cityName) return;
    
    // 模拟区县数据
    const districtData = {
        '北京市-北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区'],
        '上海市-上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '浦东新区'],
        '广东省-广州市': ['天河区', '越秀区', '海珠区', '荔湾区', '白云区'],
        '广东省-深圳市': ['福田区', '罗湖区', '南山区', '宝安区', '龙岗区'],
        '浙江省-杭州市': ['上城区', '下城区', '江干区', '拱墅区', '西湖区'],
        '江苏省-南京市': ['玄武区', '秦淮区', '建邺区', '鼓楼区', '浦口区']
    };
    
    const key = `${provinceName}-${cityName}`;
    const districts = districtData[key] || ['其他区'];
    const districtSelect = document.getElementById('district');
    districtSelect.innerHTML = '<option value="">请选择区县</option>';
    
    districts.forEach(district => {
        const option = document.createElement('option');
        option.value = district;
        option.textContent = district;
        if (selectedDistrict === district) {
            option.selected = true;
        }
        districtSelect.appendChild(option);
    });
    
    districtSelect.disabled = false;
}

// 设置默认地址
function setDefaultAddress(addressId) {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    let addresses = JSON.parse(localStorage.getItem('addresses')) || [];
    
    addresses = addresses.map(addr => {
        if (addr.userId === currentUser.id) {
            return { ...addr, isDefault: addr.id === addressId };
        }
        return addr;
    });
    
    localStorage.setItem('addresses', JSON.stringify(addresses));
    loadAddresses();
    alert('默认地址设置成功');
}

// 编辑地址
function editAddress(addressId) {
    openAddressModal(addressId);
}

// 删除地址
function deleteAddress(addressId) {
    if (confirm('确定要删除此地址吗？')) {
        let addresses = JSON.parse(localStorage.getItem('addresses')) || [];
        addresses = addresses.filter(addr => addr.id !== addressId);
        localStorage.setItem('addresses', JSON.stringify(addresses));
        loadAddresses();
        alert('地址已删除');
    }
}